#include "util.hpp"
#include "level.hpp"
#include "format.hpp"
#include "sink.hpp"
#include"buffer.hpp"
#include "logger.hpp"
#include"mylog.h"
/*
    扩展一个以时间作为日志切换的滚动类型 的日志落地模块
    1.以时间作为文件滚动，实际上是以时间段进行滚动
    实现思想：以当前系统时间，取模时间段大小，可以得到当前时间段时第几个时间段
    每次取模判断与当前文件的时间段是否一致，不一致代表不在一个时间段
    time(nullptr)%gap;11
    time(nullptr)%60 ==10 当前是第n个60秒
*/
enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};
class RollByTimeSink : public mylog::LogSink
{
public:
    // 构造时传入文件名，打开文件，并将操作句柄管理起来
    RollByTimeSink(const std::string &basename, TimeGap gap_type)
        : _basename(basename)
    {
        switch (gap_type)
        {
        case TimeGap::GAP_SECOND:
            _gap_size = 1;
            break;
        case TimeGap::GAP_MINUTE:
            _gap_size = 60;
            break;
        case TimeGap::GAP_HOUR:
            _gap_size = 3600;
            break;
        case TimeGap::GAP_DAY:
            _gap_size = 3600 * 24;
            break;
        }
        _cur_gap = _gap_size == 1 ? mylog::util::Date::now() : mylog::util::Date::now() % _gap_size; // 获取当前是第几个时间段
        std::string filename = createNewFile();
        mylog::util::File::createDirectory(mylog::util::File::getPath(filename));
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }
    // 将日志消息写入到指定文件，判断当前时间是否是当前文件的时间段，不是则切换文件
    void log(const char *data, size_t len) override
    {
        time_t cur = mylog::util::Date::now();
        if ((cur % _gap_size) != _cur_gap)
        {
            _ofs.close();
            std::string filename = createNewFile();
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }
        _ofs.write(data, len);
        assert(_ofs.good());
    }

private:
    std::string createNewFile()
    {
        time_t t = mylog::util::Date::now();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream filename;
        filename << _basename;
        filename << lt.tm_year + 1900;
        filename << lt.tm_mon + 1;
        filename << lt.tm_mday;
        filename << lt.tm_hour;
        filename << lt.tm_min;
        filename << lt.tm_sec;
        filename << ".log";

        return filename.str();
    }

private:
    std::string _basename;
    std::ofstream _ofs;
    size_t _cur_gap;  // 当前是第几个时间段
    size_t _gap_size; // 时间段的大小
};


void test_log()
{
    // mylog::Logger::ptr logger = mylog::LoggerManager::getInstance().getLogger("async_logger");
    // logger->debug("%s","测试日志");
    // logger->info("%s","测试日志");
    // logger->warn("%s","测试日志");
    // logger->error("%s","测试日志");
    // logger->fatal("%s","测试日志");

    // size_t count = 0;
    // std::string str = "测试日志-";
    // while (count<500000)
    // {
    //     logger->fatal("测试日志-%d",count++);
    // }


    
    DEBUG("%s","测试日志");
    INFO("%s","测试日志");
    WARN("%s","测试日志");
    FATAL("%s","测试日志");
    ERROR("%s","测试日志");

    size_t count = 0;
    std::string str = "测试日志-";
    while (count<500000)
    {
        FATAL("测试日志-%d",count++);
    }
}
int main()
{
    // 读取文件数据，一点点写入缓冲区，最终将缓冲区数据写入文件，判断两文件数据是否一致
    // std::ifstream ifs("./logfile/test.log", std::ios::binary);
    // if (ifs.is_open() == false)
    // {
    //     std::cout << "open faild\n";
    //     return -1;
    // }
    // ifs.seekg(0, std::ios::end); // 读写位置跳转到文件末尾
    // size_t fsize = ifs.tellg();  // 获取当前读写位置相对于起始位置的偏移量
    // ifs.seekg(0, std::ios::beg); // 重新回到起始位置
    // std::string body;
    // body.resize(fsize);
    // ifs.read(&body[0], fsize);
    // if (ifs.good() == false)
    // {
    //     std::cout << "read error\n";
    //     return -1;
    // }
    // ifs.close(); 
    // std::cout<<fsize<<std::endl;
    // mylog::Buffer buffer;

    // for(int i = 0;i<body.size();i++)
    // {
    //     buffer.push(&body[i],1); 
    // }
    // std::cout<<buffer.readAbuleSize()<<std::endl;
    // std::ofstream ofs("./logfile/tmp.log",std::ios::binary);


    // //ofs.write(buffer.begin(),buffer.readAbuleSize());
    // size_t rsize = buffer.readAbuleSize();
    // for(int i = 0;i<rsize;i++)    
    // {
    //     ofs.write(buffer.begin(),1);
    //     buffer.moveReader(1);
    // }
    // if (ofs.good() == false)
    // {
    //     std::cout << "write error\n";
    //     return -1;
    // }
    // ofs.close();


    std::unique_ptr<mylog::LoggerBuilder> builder(new mylog::GlobalLoggerBuilder());
    builder->buildLoggerLevel(mylog::LogLevel::value::WARN);
    builder->buildLoggerName("async_logger");
    builder->buildEnableUnSafeAsync();
    builder->buildFormatter("[%c][%f:%l]%m%n");
    builder->buildLoggerType(mylog::LoggerType::LOGGER_ASYNC);
    builder->buildSink<mylog::FileSink>("./logfile/async.log");
    builder->buildSink<mylog::StdoutSink>();
    builder->build();

    test_log();
    // std::string loger_name = "sync_logger";
    // mylog::LogLevel::value limit = mylog::LogLevel::value::WARN;
    // mylog::Formatter::ptr fmt(new mylog::Formatter());
    // mylog::LogSink::ptr stdout_lsp = mylog::SinkFactory::create<mylog::StdoutSink>();
    // mylog::LogSink::ptr file_lsp = mylog::SinkFactory::create<mylog::FileSink>("./logfile/test.log");
    // mylog::LogSink::ptr roll_lsp = mylog::SinkFactory::create<mylog::RollBySizeSink>("./logfile/roll-", 1024 * 1024);
    // std::vector<mylog::LogSink::ptr> sinks = {stdout_lsp,file_lsp,roll_lsp};
    // mylog::Logger::ptr logger(new mylog::SyncLogger(loger_name,limit,fmt,sinks));

    // logger->debug(__FILE__,__LINE__,"%s","测试日志");
    // logger->info(__FILE__,__LINE__,"%s","测试日志");
    // logger->warn(__FILE__,__LINE__,"%s","测试日志");
    // logger->error(__FILE__,__LINE__,"%s","测试日志");
    // logger->fatal(__FILE__,__LINE__,"%s","测试日志");

    // size_t count = 0;
    // std::string str = "测试日志-";
    // while (count<500000)
    // {
    //     logger->fatal(__FILE__,__LINE__,"测试日志-%d",count++);
    // }

    // mylog::LogMsg msg(mylog::LogLevel::value::INFO, 30, "main.c", "root", "格式化功能测试...");
    // // mylog::Formatter fmt("abc%%abc[]%d{%H:%M:%S%m%n");
    // mylog::Formatter fmt;
    // std::string str = fmt.format(msg);
    // // mylog::LogSink::ptr stdout_lsp = mylog::SinkFactory::create<mylog::StdoutSink>();
    // // mylog::LogSink::ptr file_lsp = mylog::SinkFactory::create<mylog::FileSink>("./logfile/test.log");
    // // mylog::LogSink::ptr roll_lsp = mylog::SinkFactory::create<mylog::RollBySizeSink>("./logfile/roll-", 1024 * 1024);
    // mylog::LogSink::ptr time_lsp = mylog::SinkFactory::create<RollByTimeSink>("./logfile/roll-", TimeGap::GAP_SECOND);
    // time_t old = mylog::util::Date::now();
    // while (mylog::util::Date::now() < old + 5)
    // {
    //     time_lsp->log(str.c_str(), str.size());
    // }

    // size_t count = 0;
    // stdout_lsp->log(str.c_str(), str.size());
    // file_lsp->log(str.c_str(), str.size());
    // size_t cur_size = 0;
    // while (cur_size < 1024 * 1024 * 10)
    // {
    //     std::string tmp = str + std::to_string(count++);
    //     roll_lsp->log(tmp.c_str(), tmp.size());
    //     cur_size += tmp.size();
    // }

    // std::cout<<mylog::LogLevel::toString(mylog::LogLevel::value::DEBUG)<<std::endl;
    // std::cout<<mylog::LogLevel::toString(mylog::LogLevel::value::ERROR)<<std::endl;
    // std::cout<<mylog::LogLevel::toString(mylog::LogLevel::value::FATAL)<<std::endl;
    // std::cout<<mylog::LogLevel::toString(mylog::LogLevel::value::INFO)<<std::endl;
    // std::cout<<mylog::LogLevel::toString(mylog::LogLevel::value::OFF)<<std::endl;
    // std::cout<<mylog::LogLevel::toString(mylog::LogLevel::value::UNKNOW)<<std::endl;

    // std::cout<<mylog::util::Date::now()<<std::endl;
    // std::string pathname ="./abc/def/a.txt";
    // mylog::util::File::createDirectory(mylog::util::File::getPath(pathname));
    return 0;
}